﻿using NLog;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using WTAppletProjectHTTPS.Models;

namespace WTAppletProjectHTTPS.Controllers
{
    public class HeadDataListController : ApiController
    {
        private static readonly Logger Logger = NLog.LogManager.GetCurrentClassLogger();
        public class ResultClass
        {
            public int HeadID { get; set; }

            public string HeadDate { get; set; }

            public DateTime? HeadDateTime { get; set; }

            public string HeadCreator { get; set; }

            public string HeadFormName { get; set; }

            public string HeadForm { get; set; }
            
            public string ImagesPath { get; set; }
        }
        public async Task<HttpResponseMessage> Post()
        {
            ReturnObjectQuery RO = new ReturnObjectQuery();
            try
            {
                using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionName"].ConnectionString))
                {
                    await connection.OpenAsync();
                    var query = $@"select top 3 * from (
select * from (select top 3 PADID HeadID,PADCreateTime HeadDate,PADCreateCreator HeadCreator,'成品关联模组生产日期' as HeadFormName,'ProductAssociationDate' as HeadForm,PADModuleProductionDatePhotoScan ImagesPath  
from ProductAssociationDate where PADCreateTime IS NOT NULL order by PADCreateTime desc) PAD
union 
select * from (select top 3 TSCMCID HeadID,TSCMCCreateTime HeadDate,TSCMCCreateCreator HeadCreator,'测试站换型物料确认' as HeadFormName,'TestStationChangeMaterialConfirmation' as HeadForm,TSCMCNonconformanceImage ImagesPath 
from TestStationChangeMaterialConfirmation where TSCMCCreateTime IS NOT NULL order by TSCMCCreateTime desc) TSCMC
union
select * from (select top 3 FSCMCID HeadID,FSCMCCreateTime HeadDate,FSCMCCreateCreator HeadCreator,'扣边框站换型物料确认' as HeadFormName,'FrameStationChangeMaterialConfirmation' as HeadForm,FSCMCNonconformanceImage ImagesPath 
from FrameStationChangeMaterialConfirmation where FSCMCCreateTime IS NOT NULL order by FSCMCCreateTime desc) FSCMC
union 
select * from (select top 3 LMSSCID HeadID,LMSSCCreateTime HeadDate,LMSSCCreateCreator HeadCreator,'镭雕站换型自检确认' as HeadFormName,'LaserMarkingStationSelfInspectionConfirmation' as HeadForm,LMSSCNonconformanceImage ImagesPath 
from LaserMarkingStationSelfInspectionConfirmation where LMSSCCreateTime IS NOT NULL order by LMSSCCreateTime desc) LMSSC
union
select * from (select top 3 PSCICID HeadID,PSCICCreateTime HeadDate,PSCICCreateCreator HeadCreator,'包装站换型信息确认' as HeadFormName,'PackagingStationChangeInformationConfirmation' as HeadForm,CONCAT(PSCICPlasticBagFilmPhoto, PSCICThermalTransferLabelPhoto, PSCICColorBoxPhoto,PSCICColorBoxLabelPhoto, PSCICOuterBoxLabelPhoto) AS ImagesPath 
from PackagingStationChangeInformationConfirmation where PSCICCreateTime IS NOT NULL order by PSCICCreateTime desc) PSCIC
union
select * from (select top 3 CPFIRID HeadID,CPFIRCreateTime HeadDate,CPFIRCreateCreator HeadCreator,'Cola 生产全检记录' as HeadFormName,'ColaProductionFullInspectionRecord' as HeadForm,'' as ImagesPath  
from ColaProductionFullInspectionRecord where CPFIRCreateTime IS NOT NULL order by CPFIRCreateTime desc) CPFIR
union 
select * from (select top 3 CFPID HeadID,CFPCreateTime HeadDate,CFPCreateCreator HeadCreator,'Cola首件/巡检记录' as HeadFormName,'ColaFirstPiecePatrolInspectionRecord' as HeadForm,CONCAT(CFPNonconformanceImage1,CFPNonconformanceImage2,CFPNonconformanceImage3,CFPNonconformanceImage4) as ImagesPath 
from ColaFirstPiecePatrolInspectionRecord where CFPCreateTime IS NOT NULL order by CFPCreateTime desc) CFP 
union 
select * from (select top 3 CFIRID HeadID,CFIRCreateTime HeadDate,CFIRCreateCreator HeadCreator,'Cola终检检验记录' as HeadFormName,'ColaFinalInspectionRecord' as HeadForm,CONCAT(CFIRNonconformanceImage1,CFIRNonconformanceImage2,CFIRNonconformanceImage3) ImagesPath 
from ColaFinalInspectionRecord where CFIRCreateTime IS NOT NULL order by CFIRCreateTime desc) CFIR 
union 
select * from (select top 3 CPFTID HeadID,CPFTCreateTime HeadDate,CPFTCreateCreator HeadCreator,'Cola 产品功能测试' as HeadFormName,'ColaProductFunctionTest' as HeadForm,'' as ImagesPath 
from ColaProductFunctionTest where CPFTCreateTime IS NOT NULL order by CPFTCreateTime desc) CPFT 
union 
select * from (select top 3 CPFIID HeadID,CPFICreateTime HeadDate,CPFICreateCreator HeadCreator,'Cola产线包装后全检' as HeadFormName,'ColaPackingFinalInspection' as HeadForm,'' as ImagesPath 
from ColaPackingFinalInspection where CPFICreateTime IS NOT NULL order by CPFICreateTime desc) CPFT 
union 
select * from (select top 3 QCSID HeadID,QCSCreateTime HeadDate,QCSCreateCreator HeadCreator,'QC抽检成品边框' as HeadFormName,'QCSamplingFinishedFrame' as HeadForm,QCSPhotoUpload as ImagesPath 
from QCSamplingFinishedFrame where QCSCreateTime IS NOT NULL and QCSFormType = 'TS Cola生产自检' order by QCSCreateTime desc) CPFT 
union 
select * from (select top 3 FFCID HeadID,FFCCreateTime HeadDate,FFCCreateCreator HeadCreator,'A1/A2员工边框上料确认' as HeadFormName,'A1A2EmployeeFrameFeedingConfirmation' as HeadForm,FFCPhotoUpload as ImagesPath 
from A1A2EmployeeFrameFeedingConfirmation where FFCCreateTime IS NOT NULL and FFCFormType = 'TS Cola生产自检' order by FFCCreateTime desc) CPFT ) Tatol order by Tatol.HeadDate desc";
                    using (var command = new SqlCommand(query, connection))
                    {
                        
                        using (var reader = await command.ExecuteReaderAsync())
                        {
                            if (!reader.HasRows)
                            {
                                Logger.Warn("未找到记录");
                                RO.Status = HttpStatusCode.NotFound;
                                RO.Message = "未找到记录";
                                RO.Data = null;
                                return Request.CreateResponse(HttpStatusCode.NotFound, RO);
                            }
                            var products = new List<ResultClass>();
                            int totalCount = 0;
                            while (await reader.ReadAsync())
                            {
                                //if (totalCount == 0)
                                //{
                                //    totalCount = reader.GetInt32(reader.GetOrdinal("TotalCount"));
                                //}
                                string HDString = "";
                                if ((DateTime.Now.Date.Day - reader.GetDateTime(reader.GetOrdinal("HeadDate")).Date.Day) == 0)
                                {
                                    HDString = "今天 "+ reader.GetDateTime(reader.GetOrdinal("HeadDate")).Hour+":"+ reader.GetDateTime(reader.GetOrdinal("HeadDate")).Minute;
                                }
                                else if((DateTime.Now.Date.Day - reader.GetDateTime(reader.GetOrdinal("HeadDate")).Date.Day) == 1)
                                {
                                    HDString = "昨天 " + reader.GetDateTime(reader.GetOrdinal("HeadDate")).Hour + ":" + reader.GetDateTime(reader.GetOrdinal("HeadDate")).Minute;
                                }
                                else if((DateTime.Now.Date.Day - reader.GetDateTime(reader.GetOrdinal("HeadDate")).Date.Day) == 2)
                                {
                                    HDString = "前天 " + reader.GetDateTime(reader.GetOrdinal("HeadDate")).Hour + ":" + reader.GetDateTime(reader.GetOrdinal("HeadDate")).Minute;
                                }
                                else
                                {
                                    HDString = reader.GetDateTime(reader.GetOrdinal("HeadDate")).Date.ToString("yyyy-MM-dd")+" " + reader.GetDateTime(reader.GetOrdinal("HeadDate")).Hour + ":" + reader.GetDateTime(reader.GetOrdinal("HeadDate")).Minute;
                                }
                                products.Add(new ResultClass
                                {
                                    HeadID = reader.GetInt32(reader.GetOrdinal("HeadID")),
                                    HeadDate = HDString,
                                    HeadDateTime = reader.GetDateTime(reader.GetOrdinal("HeadDate")),
                                    HeadCreator = reader.GetString(reader.GetOrdinal("HeadCreator")),
                                    HeadFormName = reader.GetString(reader.GetOrdinal("HeadFormName")),
                                    HeadForm = reader.GetString(reader.GetOrdinal("HeadForm")),
                                    ImagesPath = reader.GetString(reader.GetOrdinal("ImagesPath"))
                                });
                            }

                            Logger.Info("查询成功");
                            RO.Status = HttpStatusCode.OK;
                            RO.Message = "OK";
                            RO.Data = products;
                            RO.TotalCount = 3;
                            return Request.CreateResponse(HttpStatusCode.OK, RO);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Error("查询失败: " + ex.Message);
                RO.Status = HttpStatusCode.InternalServerError;
                RO.Message = "Error: " + ex.Message;
                RO.Data = null;
                return Request.CreateResponse(HttpStatusCode.InternalServerError, RO);
            }
        }

    }
}